import {getInfo, getMenus, GetValidateCode, loginByPassword, logout} from '@/api/login';
import {getToken, removeToken, setToken} from '@/utils/auth';
import { Toast } from 'mint-ui';

import Layout from '@/views/layout/Layout';

const _import = require('@/router/_import_' + process.env.NODE_ENV)

function calcute(menus) {

  for (let i = 0; i < menus.length; i++) {
    if (menus[i].function_id === 76) {
      menus.splice(i, 1);
      break;
    }
  }
  let asyncRouterMap = [];
  for (let i = 0; i < menus.length; i++) {
    //console.log(menus[i].function_id)

    asyncRouterMap[i] = {};
    asyncRouterMap[i].path = "/" + menus[i].function_url;
    asyncRouterMap[i].name = menus[i].function_name;
    asyncRouterMap[i].icon = menus[i].function_icon;
    asyncRouterMap[i].remark = menus[i].function_remark;
    asyncRouterMap[i].component = Layout;

    if (menus[i].children && menus[i].children.length) {
      asyncRouterMap[i].children = [];
      for (let j = 0; j < menus[i].children.length; j++) {
        asyncRouterMap[i].children[j] = {}
        try {
          asyncRouterMap[i].children[j].component = _import(menus[i].function_url + "/" + menus[i].children[j].function_url + "/index");
        } catch (e) {
          asyncRouterMap[i].children[j].component = _import("errorPage/404");
        }
        asyncRouterMap[i].children[j].path = menus[i].children[j].function_url;
        asyncRouterMap[i].children[j].name = menus[i].children[j].function_name;
        asyncRouterMap[i].children[j].icon = menus[i].children[j].function_icon;
        asyncRouterMap[i].children[j].remark = menus[i].children[j].function_remark;


      }
    } else {
      asyncRouterMap[i].redirect = menus[i].function_url + "main";
      asyncRouterMap[i].children = [];
      asyncRouterMap[i].children[0] = {}
      asyncRouterMap[i].children[0].name = menus[i].function_name;
      asyncRouterMap[i].children[0].icon = menus[i].function_icon;
      asyncRouterMap[i].children[0].path = menus[i].function_url + "main"
      asyncRouterMap[i].children[0].remark = menus[i].children[j].function_remark;
      try {
        asyncRouterMap[i].children[0].component = _import(menus[i].function_url + "/index");
      } catch (e) {
        asyncRouterMap[i].children[0].component = _import("errorPage/404");
      }
    }
  }
  return asyncRouterMap;
}

const user = {
  state: {
    user_id: 0,
    login_name: '',
    real_name: '',
    before_name: '',
    mobile: '',
    health: '',
    birthday: undefined,
    sex: undefined,
    idcode: undefined,
    nation: undefined,
    marriage: undefined,
    native_place: undefined,
    political_status: undefined,
    email: undefined,
    home_address: undefined,
    shops: [],
    roles: [],
    menus: undefined,
    elements: undefined,
    permissionMenus: undefined,
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_USER_INFO: (state, user) => {
      state.user_id = user.user_id;
      state.login_name = user.login_name;
      state.real_name = user.real_name;
      state.before_name = user.before_name;
      state.mobile = user.mobile;
      if (user.health != null) {
        state.health = user.health;
      } else {
        state.health = '';
      }
      state.birthday = user.birthday;
      state.sex = user.sex;
      state.idcode = user.idcode;
      state.nation = user.nation;
      state.marriage = user.marriage;
      state.native_place = user.native_place;
      state.political_status = user.political_status;
      state.email = user.email;
      state.home_address = user.home_address;
    },
    SET_SHOPS: (state, shops) => {
      state.shops = shops;
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus;
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements;
    },
    LOGIN_SUCCESS: () => {
      console.log('登录成功！')
    },
    LOGOUT_USER: state => {
      state.user_id = 0;
      state.login_name = ''
      state.real_name = ''
      state.before_name = ''
      state.mobile = ''
      state.health = ''
      state.birthday = undefined
      state.sex = undefined
      state.idcode = undefined
      state.nation = undefined
      state.marriage = undefined
      state.native_place = undefined
      state.political_status = undefined
      state.email = undefined
      state.home_address = undefined
    },
    SET_PERMISSION_MENUS: (state, permissionMenus) => {
      state.permissionMenus = permissionMenus;
    }
  },

  actions: {
    // 用户及密码登录
    LoginByPassword({commit}, userInfo) {
      commit('LOGOUT_USER');
      commit('SET_MENUS', undefined);
      commit('SET_ELEMENTS', undefined);
      removeToken();
      return new Promise((resolve, reject) => {
        loginByPassword(userInfo).then(response => {
          const data = response;
          if (data.status === 200) {
            setToken(data.data);
            resolve();
          } else {
            Toast({
              message: data.message,
              position: 'bottom',
              duration: 5000
            });
            return Promise.reject('error');
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 获取用户信息
    GetUserInfo({commit, state}) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          if (response.status === 200) {
            const data = response.data;

            commit('SET_USER_INFO', data);
            for (let i = 0; i < data.shop_ids.length; i++) {
              data.shop_ids[i].shop_index = i;
            }

            commit('SET_SHOPS', data.shop_ids);
            commit('SET_MENUS', calcute(data.menus));
            const elements = {};
            for (let i = 0; i < data.elements.length; i++) {
              elements[data.elements[i].function_url] = true;
            }
            commit('SET_ELEMENTS', elements);
            resolve(response);
          } else {
            resolve(response);
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 登出
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('LOGOUT_USER', undefined);
          commit('SET_MENUS', undefined);
          commit('SET_ELEMENTS', undefined);
          commit('SET_PERMISSION_MENUS', undefined);
          removeToken();
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 前端 登出
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('LOGOUT_USER', undefined);
        commit('SET_MENUS', undefined);
        commit('SET_ELEMENTS', undefined);
        commit('SET_PERMISSION_MENUS', undefined);
        removeToken();
        resolve();
      });
    }
  }
};

export default user;
